// 引入接口文件
import { addFun,editFun,getAllProductType,queryInfo,getTreeData,deleteFun} from './predictListServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  modelObj: {
    btnLoading: false,
  },
  tableObj: {
    key: '',
    mdmProductType:'',//  主数据产品类型
    mdmCode: '', //   主数据产品编码对应 主数据接口返回的id
    creator: '',// 创建人 
    createTime: '',// YY-mm-DD  HH:MM  当前时间
  },
  treeObj: {
    key:'',
    proCode:'',
    proName: ''
  },
  treeList: [],
  tableData:[],
  distributionNameList: [],
  loading: false,
  keys: 0,
  treeKeys: 0,
  id: '',
  proId:'',
  actionType: 'add',
  tableShow: false,
  query: {
    productTabName: '一级分类',//分类
    productStatus: '0', //状态
    productCode: '', //产品状编码
    productName: '',//字段名称
    ProductType: []
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态

          dispatch({type: 'getAllProductType',payload: {id:query.id}})
          dispatch({type: 'getTreeData',payload: {}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
      // 查询记录
      *getAllProductType({payload}, {put, select, call}){
          let {treeList,treeKeys} = yield select(state => state[tmpModule.namespace])
          let params = {}
          const { success,result} = yield call(getAllProductType, {...params})
          if(success){
            treeKeys = result.length
            treeList = result
            yield put({
              type: 'updateStore',
              payload: {treeList,treeKeys}
            })
          }
      },
      // 查询记录
      *queryInfo({payload}, {put, select, call}){
          let {query,tableData} = yield select(state => state[tmpModule.namespace])
          let params = {id: payload.id}
          const { success,result} = yield call(queryInfo, {...params})
          if(success){
            query = result
            tableData = result.ProductType
            yield put({
              type: 'updateStore',
              payload: {query,tableData}
            })
          }
      },
      // 查询主数据
      *getTreeData({payload}, {put, select, call}){
          let {distributionNameList} = yield select(state => state[tmpModule.namespace])
          let params = {}
          const { success,result} = yield call(getTreeData, {...params})
          // if(success){
            let jsonData = JSON.parse(result).body.list
            //temp为临时对象，将json数据按照id值排序.
            var arr = [], temp = {}, len = jsonData.length
            for(var item of jsonData){
              item.title = item.name
              item.value = item.code
              item.key = item.id
            }
            for(var i = 0; i < len; i++){
                // 以id作为索引存储元素，可以无需遍历直接快速定位元素
                temp[jsonData[i]['id']] = jsonData[i] 
            }
            for(var j = 0; j < len; j++){
                var list = jsonData[j]
                // 临时变量里面的当前元素的父元素，即pid的值，与找对应id值
                var sonlist = temp[list['parentId']] 
                // 如果存在父元素，即如果有pid属性
                if (sonlist) { 
                    // 如果父元素没有children键
                    if (!sonlist['children']) { 
                    // 设上父元素的children键
                    sonlist['children'] = [] 
                    }
                    // 给父元素加上当前元素作为子元素
                    sonlist['children'].push(list) 
                } 
                // 不存在父元素，意味着当前元素是一级元素
                else { 
                  arr.push(list);
                }
            }
            distributionNameList = arr
            yield put({
              type: 'updateStore',
              payload: {distributionNameList}
            })
          // }
      },
      *submit({payload},{put,select,call}){
        let {query,tableData,proId,tableShow} = yield select(state => state[tmpModule.namespace])
        query.ProductType = tableData
        let params = query
        if(!params.ProductType.length){
          message.warn('关联主数据产品不能为空')
          return false
        }
        const { success, msg, data } = yield call(addFun, {...params})
        if(success){
          message.success('保存成功')
          tableShow = false
          yield put({type: 'getAllProductType',payload: {}})
          yield put({
            type: 'updateStore',
            payload: {tableShow}
          })
        }
      },
      *deleteFun({payload},{put,select,call}){
        let {proId} = yield select(state => state[tmpModule.namespace])
        let params = {
          id: proId
        }
        const { success, msg, data } = yield call(deleteFun, {...params})
        if(success){
          message.success('删除成功')
          yield put({type: 'getAllProductType',payload: {}})
        }
      }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
